<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>{{ $t('licence.pro_title') }}</span>
            </div>
          </template>
          <div>
            <div class="text-center flexBetween">
              <div class="userTop">
                <userAvatar :user="user" />
                <div class="userNameId">
                  <p class="userName">
                    {{ user.userName }}
                    <span style="margin-left: 8px; cursor: pointer" @click="ziliao"><img
                        src="../../../../assets/images/bi.png" alt="" /></span>
                  </p>
                  <div class="ziliao">
                    <p class="userId">{{ $t('licence.pro_userId') }}{{ dept.code }}</p>
                    <p class="userId">{{ $t('licence.pro_deptName') }}{{ dept.deptName }}</p>
                    <p class="userId">
                      {{ $t('licence.pro_sex') }}<span v-if="userInfo.sex == 0">{{ $t('licence.pro_sex0') }}</span>
                      <span v-if="userInfo.sex == 1">{{ $t('licence.pro_sex1') }}</span>
                      <span v-if="userInfo.sex == 2">{{ $t('licence.pro_sex2') }}</span>
                    </p>
                  </div>
                </div>
              </div>
              <div>
                <el-button type="info" round @click.native="logout">{{ $t('licence.pro_logout') }}</el-button>
              </div>
            </div>
          </div>
          <ul>
            <li class="mainS flexBetween">
              <div class="main-content">
                <span class="contentL email">{{ $t('licence.pro_email') }}</span>
                <span class="contentM">
                  <!-- 未绑定 -->
                  <span v-if="!userInfo.email">
                    <span class=""> <img class="iocn" src="../../../../assets/images/duiNo.png" alt="" /></span>
                    <span class="contentM">{{ $t('licence.pro_wei') }}</span>
                  </span>
                  <!-- 已绑定 -->
                  <span v-else>
                    <span class=""> <img class="iocn" src="../../../../assets/images/dui.png" alt="" /></span>
                    <span class="contentM">
                      {{ $t('licence.pro_yi') }}
                      {{ userInfo.email.replace(/^(.{2})[^@]+(?=.{2}@)/, '$1****') }}</span>
                  </span>
                </span>
              </div>
              <div>
                <el-button type="success" @click="getEmail">{{ $t('licence.pro_getEmail') }}</el-button>
              </div>
            </li>
            <li class="mainS flexBetween">
              <div class="main-content">
                <span class="contentL email">{{ $t('licence.pro_phonenumber') }}</span>
                <span class="contentM">
                  <!-- 未绑定 -->
                  <span v-if="!userInfo.phonenumber">
                    <span class=""> <img class="iocn" src="../../../../assets/images/duiNo.png" alt="" /></span>
                    <span class="contentM">{{ $t('licence.pro_wei') }}</span>
                  </span>
                  <!-- 已绑定 -->
                  <span v-else>
                    <span class=""> <img class="iocn" src="../../../../assets/images/dui.png" alt="" /></span>
                    <span class="contentM">
                      {{ $t('licence.pro_yi') }}
                      {{ userInfo.phonenumber.replace(/^(.{3})(?:\d+)(.{4})$/, '$1****$2') }}</span>
                  </span>
                </span>
              </div>
              <div>
                <el-button type="success" @click="getPhonen">{{ $t('licence.pro_getPhonen') }}</el-button>
              </div>
            </li>
            <li class="mainS flexBetween">
              <div class="main-content">
                <span class="contentL email">{{ $t('licence.pro_pasword') }}</span>
                <span class="contentM">
                  <!-- 未绑定 -->
                  <span v-if="!userInfo.phonenumber">
                    <span class=""> <img class="iocn" src="../../../../assets/images/duiNo.png" alt="" /></span>
                    <span class="contentM">{{ $t('licence.pro_she') }}</span>
                  </span>
                  <!-- 已绑定 -->
                  <span v-else>
                    <span class=""> <img class="iocn" src="../../../../assets/images/dui.png" alt="" /></span>
                    <span class="contentM"> {{ $t('licence.pro_sheIng') }}</span>
                  </span>
                </span>
              </div>
              <div>
                <el-button type="success" @click="pasword">{{ $t('licence.pro_newPass') }}</el-button>
              </div>
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>
    <!-- 修改信息弹框 -->
    <el-dialog v-model="dialogInformation" width="30%">
      <div class="titleShow">
        <div class="titles">{{ $t('licence.pro_xiuTitle') }}</div>
      </div>
      <el-form :model="informationForm">
        <el-form-item :label="$t('licence.pro_userName')" :label-width="formLabelWidth" style="margin-bottom: 20px">
          <el-input v-model="informationForm.userName" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('licence.pro_nickName')" :label-width="formLabelWidth" style="margin-bottom: 20px">
          <el-input v-model="informationForm.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('licence.pro_deptName')" :label-width="formLabelWidth" style="margin-bottom: 20px">
          <el-input v-model="informationForm.deptName" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('licence.pro_sex')" :label-width="formLabelWidth">
          <!-- 中文 -->
          <el-select v-if="lang == 0" v-model="informationForm.sex" :placeholder="$t('licence.use_shuSex')">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <!-- 英文 -->
          <el-select v-if="lang == 1" v-model="informationForm.sex" :placeholder="$t('licence.use_shuSex')">
            <el-option v-for="dict in sys_user_sexs" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer baocun">
          <el-button @click="dialogInformation = false">{{ $t('licence.cancel') }}</el-button>
          <el-button type="primary" @click="baocun">{{ $t('licence.pro_primary') }}</el-button>
        </span>
      </template>
    </el-dialog>
    <!--更换邮箱弹框 -->
    <el-dialog v-model="dialogEmail" width="23%">
      <div class="titleShow">
        <div class="titles">{{ $t('licence.pro_updateEmail') }}</div>
      </div>
      <div v-if="newEmailS">
        <el-form :model="codeForm" ref="codeForms" class="editForm">
          <el-form-item prop="code">
            <p style="margin-bottom: 10px">{{ $t('licence.pro_baohu') }}{{ userInfo.email.replace(/(.{2})[^@]+(?=.{2}@)/,
              '$1****') }}{{ $t('licence.pro_yanzheng') }}</p>
            <div>
              <el-input v-model="codeForm.code" :placeholder="$t('licence.for_code')" class="input-with-select">
                <template #append>
                  <el-button v-if="codeShow" @click="getColde" slot="append">{{$t('licence.pro_faSongCode')}}</el-button>
                  <el-button v-if="!codeShow" slot="append">{{ count }}{{ $t('licence.pro_chongshi') }}</el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div v-else>
        <el-form ref="formEail" :model="user" :rules="rules">
          <el-form-item prop="Newemail" style="margin-bottom: 30px">
            <el-input v-model="user.Newemail" :placeholder="$t('licence.pro_newEmail')"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" class="queding" v-if="newEmailS" @click="nextStep">{{ $t('licence.nextStep')
          }}</el-button>
          <el-button class="queding" type="primary" v-else @click="determineEmail">{{ $t('licence.determine')
          }}</el-button>
        </span>
      </template>
    </el-dialog>
    <!--更换密码弹框 -->
    <el-dialog v-model="dialogPassword" width="23%">
      <div class="titleShow">
        <div class="titles">{{ $t('licence.pro_updatePass') }}</div>
      </div>
      <div v-if="newPasswordS">
        <el-form :model="codeForm" ref="codeForms" class="editForm">
          <el-form-item prop="code">
            <p style="margin-bottom: 10px">{{ $t('licence.pro_baohu') }}{{ userInfo.email.replace(/(.{2})[^@]+(?=.{2}@)/,
              '$1****') }}{{ $t('licence.pro_yanzheng') }}</p>
            <div>
              <el-input v-model="codeForm.code" :placeholder="$t('licence.for_code')" class="input-with-select">
                <template #append>
                  <el-button v-if="codeShow" @click="getColde" slot="append">{{$t('licence.pro_faSongCode')}}</el-button>
                  <el-button v-if="!codeShow" slot="append">{{ count }}{{ $t('licence.pro_chongshi') }}</el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div v-else>
        <el-form ref="form" :model="user" :rules="rules">
          <el-form-item prop="newPassword" style="margin-bottom: 30px">
            <el-input v-model="user.newPassword" :placeholder="$t('licence.pro_shuNewPass')" type="password"
              show-password />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input v-model="user.confirmPassword" :placeholder="$t('licence.pro_confirmPassword')" type="password"
              show-password />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" class="queding" v-if="newPasswordS" @click="nextStep">{{ $t('licence.nextStep')
          }}</el-button>
          <el-button type="primary" class="queding" v-else @click="determine">{{ $t('licence.determine') }}</el-button>
        </span>
      </template>
    </el-dialog>
    <!--更换手机弹框 -->
    <el-dialog v-model="dialogPhonen" width="23%">
      <div class="titleShow">
        <div class="titles">{{ $t('licence.pro_xiuPhonen') }}</div>
      </div>
      <div v-if="newPhonenS">
        <el-form :model="codeForm" ref="codeForms" class="editForm">
          <el-form-item prop="code">
            <p style="margin-bottom: 10px">{{ $t('licence.pro_baohu') }}用{{ userInfo.email.replace(/(.{2})[^@]+(?=.{2}@)/,
              '$1****') }}{{ $t('licence.pro_yanzheng') }}</p>
            <div>
              <el-input v-model="codeForm.code" :placeholder="$t('licence.for_code')" class="input-with-select">
                <template #append>
                  <el-button v-if="codeShow" @click="getColde" slot="append">{{$t('licence.pro_faSongCode')}}</el-button>
                  <el-button v-if="!codeShow" slot="append">{{ count }}{{ $t('licence.pro_chongshi') }}</el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div v-else>
        <el-form ref="formPhonen" :model="user" :rules="rules">
          <el-form-item prop="phonen" style="margin-bottom: 30px">
            <el-input v-model="user.phonen" :placeholder="$t('licence.pro_newPhonen')" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" class="queding" v-if="newPhonenS" @click="nextStep">{{ $t('licence.nextStep')
          }}</el-button>
          <el-button type="primary" class="queding" v-else @click="determinePhonen">{{ $t('licence.determine')
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Profile" setup lang="ts">
import userAvatar from './userAvatar.vue';
import { getUserProfile, setCode, updatePwd, updateEmail, updatePhoneNumber, updateUserS } from '@/api/system/user';
import useUserStore from '@/store/modules/user';
import { getidentifyingCode } from '@/api/login';
import type { FormInstance, FormRules } from 'element-plus'
const router = useRouter()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_user_sexs, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sexs', 'sys_user_sex'));
const formPhonen = ref<FormInstance>()
const formEail = ref<FormInstance>()
const form = ref<FormInstance>()
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const userInfo = ref<Record<string, any>>({
  dept: {},
  sex: 0,
  email: '',
  nickName: '',
  userName: '',
});//用户信息
const dept = ref<Record<string, any>>({});
const roleGroup = ref({});
// const activeTab = ref('userinfo');
const dialogInformation = ref(false);//修改信息弹框
const dialogPassword = ref(false);//更换密码弹框
const dialogEmail = ref(false);//修改邮箱号弹框
const dialogPhonen = ref(false);//修改手机号
const newPasswordS = ref(true);//切换表单
const newEmailS = ref(true);//切换表单邮箱
const newPhonenS = ref(true);//切换表单手机号
const codeShow = ref(true);//获取验证码倒计时
const timer = ref();//定时器
const count = ref(60); //倒计时数字
// 用户表单
interface RuleForm {
  code?: number,
  newPassword?: string | number,
  confirmPassword?: string | number,
  Newemail?: string | number
};
const codeForm = ref<RuleForm>({
  code: 1
}
);
const user = ref({
  newPassword: '',
  confirmPassword: '',
  Newemail: '',
  phonen: '',
  userName: '',
  avatar:'',
  avatarOss:'',
});
// 修改信息
const formLabelWidth = ref('130px');
const informationForm = ref({
  nickName: '',
  deptName: '',
  sex: 'male',
  userName: '',
})
const equalToPassword = (rule: any, value: any, callback: any) => {
  if (user.value.newPassword !== value) {
    callback(new Error(t('licence.pro_equalToPassword')));
  } else {
    callback();
  }
};
//修改信息弹框信息
const rules: ElFormRules = {
  newPassword: [
    {
      required: true,
      message: t('licence.mNewPass'),
      trigger: 'blur',
    },
    {
      min: 6,
      max: 20,
      message: t('licence.mNewPassG'),
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: t('licence.pro_confirmPassword'),
      trigger: 'blur',
    },
    { required: true, validator: equalToPassword, trigger: 'blur' },
  ],
  Newemail: [
    {
      required: true,
      message: t('licence.pro_newEmailMess'),
      trigger: 'blur',
    },
  ],
};
const lang = ref(0)
onMounted(() => {
  {
    // 获取用户信息
    userInfo.value = JSON.parse(localStorage.getItem('userInfo') as string);
    dept.value = userInfo.value.dept;
    // 获取语言
    if (localStorage.getItem('locale') == 'en_US') {
      lang.value = 1;
    } else {
      lang.value = 0;
    }
  }
});
const getUser = () => {
  getUserProfile().then((response) => {
    user.value = response.data.user;
    // roleGroup.value = response.roleGroup;
    // postGroup = response.postGroup;
    informationForm.value.nickName = userInfo.value.nickName;
    informationForm.value.deptName = userInfo.value.dept.deptName;
    informationForm.value.userName = userInfo.value.userName;
  });
}
getUser();

const ziliao = () => {
  dialogInformation.value = true;
  informationForm.value = {
    nickName: userInfo.value.nickName,
    deptName: userInfo.value.dept.deptName,
    userName: userInfo.value.userName,
    sex: userInfo.value.sex == 0 ? t('licence.pro_sex0') : t('licence.pro_sex1'),
  };
};
const baocun = async () => {
  let data = {
    nickName: informationForm.value.nickName,
    sex: informationForm.value.sex,
  };
  await updateUserS(data);
  ElMessage.success(t('licence.use_updateXiugai'));
  dialogInformation.value = false;
  getUser();
};
const logout = async () => {
  ElMessageBox.confirm(t('licence.pro_cancellation'), t('licence.Tips'), {
    confirmButtonText: t('licence.determine'),
    cancelButtonText: t('licence.cancel'),
    type: 'warning',
  })
    .then(async () => {
      // $store.dispatch('LogOut').then(() => {
      //   location.href = '/index';
      // });
      await useUserStore().logout();
      location.href = '/index';
      localStorage.clear();
      // localStorage.getItem
    })
    .catch(() => { });
};
//打开弹框
const pasword = () => {
  codeForm.value.code=''
  dialogPassword.value = true;
  // 获取用户信息
  userInfo.value = JSON.parse(localStorage.getItem('userInfo') as string);
};
// 更换邮箱号弹框
const getEmail = () => {
  codeForm.value.code=''
  dialogEmail.value = true;
};
// 更换手机号弹框
const getPhonen = () => {
  codeForm.value.code=''
  dialogPhonen.value = true;
};

// 更换邮箱
const determineEmail = () => {
  formEail.value?.validate((valid) => {
    if (valid) {
      let data = {
        email: user.value.Newemail,
        lang: lang.value,
      };
      updateEmail(data).then((response) => {
        proxy?.$modal.msgSuccess(t('licence.pro_genghuan'));
        // router.replace("/login");
      });
      dialogEmail.value = false;
      // router.push({
      //   path:'/system/profile',
      //   name:'Profile'
      // })
    }
  });
};
// 更换手机号
const determinePhonen = () => {
  formPhonen.value?.validate((valid) => {
    if (valid) {
      let data = {
        phonenumber: user.value.phonen,
        lang: lang.value,
      };
      updatePhoneNumber(data).then((response) => {
        proxy?.$modal.msgSuccess(t('licence.pro_genghuan'));
        // router.replace("/login");
      });
      dialogPhonen.value = false;
      // router.push({
      //   path:'/system/profile',
      //   name:'Profile'
      // })
    }
  });
};
//修改密码
const determine = () => {
  form.value?.validate((valid) => {
    if (valid) {
      let data = {
        email: userInfo.value.email,
        newPassword: user.value.newPassword,
      };
      updatePwd(data).then((response) => {
        proxy?.$modal.msgSuccess(t('licence.pro_determine'));
        router.replace('/login');
      });
    }
  });
};
//验证码倒计时
const getColde = async () => {
  await getidentifyingCode(userInfo.value.email);
  const TIME_COUNT = 60;
  if (!timer.value) {
    count.value = TIME_COUNT;
    codeShow.value = false;
    timer.value = setInterval(() => {
      if (count.value > 0 && count.value <= TIME_COUNT) {
        count.value--;
      } else {
        codeShow.value = true;
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);
  }
};
// 验证验证码
const nextStep = async () => {
  if (dialogPassword.value) {
    newPasswordS.value = true;
    if (!codeForm.value.code) {
      ElMessage({
        message: t('licence.for_code'),
        type: 'warning',
      });
      return;
    }
    let res = await setCode({
      email: userInfo.value.email,
      identifyingCode: codeForm.value.code,
      lang: lang.value,
    });
    if (res.code == 200) {
      newPasswordS.value = false;
      // newEmailS.value = false;
    }
  } else if (dialogEmail.value) {
    newEmailS.value = true;
    if (!codeForm.value.code) {
      ElMessage({
        message: t('licence.for_code'),
        type: 'warning',
      });
      return;
    }
    let res = await setCode({
      email: userInfo.value.email,
      identifyingCode: codeForm.value.code,
      lang: lang.value,
    });
    if (res.code == 200) {
      // newPasswordS.value = false;
      newEmailS.value = false;
    }
  } else {
    newPhonenS.value = true;
    if (!codeForm.value.code) {
      ElMessage({
        message: t('licence.for_code'),
        type: 'warning',
      });
      return;
    }
    let res = await setCode({
      email: userInfo.value.email,
      identifyingCode: codeForm.value.code,
      lang: lang.value,
    });
    if (res.code == 200) {
      // newPasswordS.value = false;
      newPhonenS.value = false;
    }
  }
};
</script>
<style scoped lang="scss">
.titleShow {
  display: flex;
  cursor: pointer;
  font-size: 16px;
  margin-right: 24px;
  font-weight: 600;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  width: 100%;
  padding-bottom: 20px;

  .titles {
    margin-right: 24px;
  }
}

::v-deep .el-dialog__header {
  padding: 0 !important;
  padding-bottom: 0;
}

::v-deep .el-dialog {
  border-radius: 6px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

.text-center {
  text-align: left !important;
  padding: 28px 10px 30px 40px;
  border-radius: 4px;
  background: linear-gradient(90deg, #e2e7f7 0%, #d6dfef 38%, #d0dbec 100%, #f5f8fa 100%);

  .userTop {
    // width: 300px !important;
    display: flex;

    .userNameId {
      margin-left: 25px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      align-self: center;

      .userName {
        font-size: 20px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: #2b2b2b;
        margin-bottom: 10px;
      }

      .ziliao {
        display: -webkit-box;

        .userId {
          margin-right: 30px;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #797f89;
        }
      }
    }
  }
}

ul {
  padding: 0;

  .mainS {
    background: #ffffff;
    border-bottom: 1px solid #dfe5ea;
    padding: 40px 40px 30px 40px;

    .contentL {
      width: 110px;
      display: inline-block;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #2b2b2b;
    }

    .contentM {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #2b2b2b;
    }

    // 查询按钮
  }

  .el-button--success {
    color: #ffffff;
    background-color: #305add;
    border-color: #305add;
  }
}

.editForm {
  display: flex;
}

::v-deep .el-input-group__append button.el-button {
  background: #1267fa;
  color: #fff;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

// 下一步
.dialog-footer {
  display: flex;
  justify-content: center;
}

// 确定按钮
.queding {
  width: 330px !important;
  height: 40px !important;
  background: #1267fa !important;
  border-radius: 20px !important;
}

.baocun {
  display: block;
}

.el-button--primary {
  background: #1267fa !important;
}

.iocn {
  width: 20px;
  height: 21px;
  vertical-align: middle;
  margin-right: 8px;

  .img {
    width: 100%;
    height: 100%;
  }
}

::v-deep .el-input-group__append {
  color: #ffffff;
  background-color: #305add;
  border-color: #305add;
  box-shadow: none !important;
  cursor: pointer;
  border-radius: 0px !important;
}
</style>
